import 'package:flutter/material.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/services/video_thumbnail_service.dart';
import 'package:hinge/common/models/video_comment_model.dart';
import 'package:hinge/common/services/video_comment_service.dart';

class VideoService {
  static const String _spKey = 'video_list';

  // 初始化视频数据
  static Future<void> initVideoData() async {
    // 先初始化评论数据
    await VideoCommentService.initSampleComments();

    // 获取所有评论以计算每个视频的评论数
    final allComments = await VideoCommentService.getAllComments();

    // 按视频ID分组并计算每个视频的评论数
    final Map<int, int> commentCounts = {};
    for (var comment in allComments) {
      commentCounts[comment.videoId] =
          (commentCounts[comment.videoId] ?? 0) + 1;
    }

    final List<VideoModel> defaultVideos = [
      VideoModel(
        id: 1,
        description:
            'The Tonality of perfume is determined by raw materials, and the top notes are usually light and refreshing...',
        url: AssetsImages.video1,
        collectCount: 1234,
        likeCount: 5678,
        commentCount: commentCounts[1] ?? 0,
        coverUrl: AssetsImages.strong1,
      ),
      VideoModel(
        id: 2,
        description:
            'The middle notes of perfume are the soul of the fragrance, usually lasting for several hours...',
        url: AssetsImages.video2,
        collectCount: 2345,
        likeCount: 6789,
        commentCount: commentCounts[2] ?? 0,
        coverUrl: AssetsImages.strong2,
      ),
      VideoModel(
        id: 3,
        description:
            'The base notes of perfume provide depth and longevity to the fragrance, often woody or musky...',
        url: AssetsImages.video3,
        collectCount: 3456,
        likeCount: 7890,
        commentCount: commentCounts[3] ?? 0,
        coverUrl: AssetsImages.strong3,
      ),
      VideoModel(
        id: 4,
        description:
            'Citrus perfumes capture the essence of sunshine with bright, energetic notes of lemon, lime, and bergamot...',
        url: AssetsImages.video4,
        collectCount: 4567,
        likeCount: 8901,
        commentCount: commentCounts[4] ?? 0,
        coverUrl: AssetsImages.strong1,
      ),
      VideoModel(
        id: 5,
        description:
            'Floral fragrances celebrate the delicate beauty of flowers, from roses to jasmine, creating a romantic aura...',
        url: AssetsImages.video5,
        collectCount: 5678,
        likeCount: 9012,
        commentCount: commentCounts[5] ?? 0,
        coverUrl: AssetsImages.strong2,
      ),
      VideoModel(
        id: 6,
        description:
            'Oriental perfumes blend exotic spices with rich resins, creating warm, sensual experiences that last all day...',
        url: AssetsImages.video6,
        collectCount: 6789,
        likeCount: 10123,
        commentCount: commentCounts[6] ?? 0,
        coverUrl: AssetsImages.strong3,
      ),
      VideoModel(
        id: 7,
        description:
            'Fougere fragrances combine lavender, oakmoss and coumarin for a fresh, sophisticated scent that is timeless...',
        url: AssetsImages.video7,
        collectCount: 7890,
        likeCount: 11234,
        commentCount: commentCounts[7] ?? 0,
        coverUrl: AssetsImages.strong1,
      ),
    ];

    // 生成视频缩略图并更新视频封面
    await _generateThumbnailsForVideos(defaultVideos);

    // 存储到 SP
    await SpUtil.setModelList(_spKey, defaultVideos);
  }

  // 为视频列表生成缩略图
  static Future<void> _generateThumbnailsForVideos(
    List<VideoModel> videos,
  ) async {
    for (int i = 0; i < videos.length; i++) {
      final VideoModel video = videos[i];

      // 生成缩略图
      try {
        final String? thumbnailPath =
            await VideoThumbnailService.generateThumbnail(video.url, video.id);

        // 如果成功生成缩略图，则更新视频封面
        if (thumbnailPath != null) {
          videos[i] = VideoModel(
            id: video.id,
            description: video.description,
            url: video.url,
            collectCount: video.collectCount,
            likeCount: video.likeCount,
            commentCount: video.commentCount,
            coverUrl: thumbnailPath,
          );
          debugPrint('视频 ${video.id} 已生成缩略图: $thumbnailPath');
        }
      } catch (e) {
        debugPrint('为视频 ${video.id} 生成缩略图失败: $e');
      }
    }
  }

  // 获取视频列表
  static List<VideoModel> getVideoList() {
    return SpUtil.getModelList(_spKey, VideoModel.fromJson);
  }

  // 更新视频数据（例如点赞、收藏等）
  static Future<void> updateVideo(VideoModel video) async {
    List<VideoModel> videos = getVideoList();
    int index = videos.indexWhere((v) => v.id == video.id);
    if (index != -1) {
      videos[index] = video;
      await SpUtil.setModelList(_spKey, videos);
    }
  }

  // 更新视频评论数
  static Future<void> updateVideoCommentCount(int videoId) async {
    final comments = await VideoCommentService.getCommentsByVideoId(videoId);
    final int commentCount = comments.length;

    List<VideoModel> videos = getVideoList();
    int index = videos.indexWhere((v) => v.id == videoId);
    if (index != -1) {
      final video = videos[index];
      final updatedVideo = VideoModel(
        id: video.id,
        description: video.description,
        url: video.url,
        coverUrl: video.coverUrl,
        collectCount: video.collectCount,
        likeCount: video.likeCount,
        commentCount: commentCount,
      );
      await updateVideo(updatedVideo);
    }
  }
}
